package com.meida.app.provider.integration.authenticator.sms;


import com.meida.app.provider.integration.authenticator.AbstractIntegrationAuthenticator;
import com.meida.app.provider.integration.authenticator.sms.event.SmsAuthenticateBeforeEvent;
import com.meida.app.provider.integration.authenticator.sms.event.SmsAuthenticateSuccessEvent;
import com.meida.app.provider.integration.model.IntegrationParams;
import com.meida.module.user.client.entity.AppAccount;
import com.meida.common.enums.AccountTypeEnum;
import com.meida.common.utils.RedisUtils;
import com.meida.module.user.provider.service.AppAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

/**
 * 短信验证码集成认证
 *
 * @author zyf
 */
@Component
public class SmsIntegrationAuthenticator extends AbstractIntegrationAuthenticator implements ApplicationEventPublisherAware {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private AppAccountService appAccountService;

    private ApplicationEventPublisher publisher;


    @Override
    public AppAccount authenticate(IntegrationParams integrationParams) {
        //获取账户名，实际值是手机号
        String accountName = integrationParams.getAccountName();
        String password = integrationParams.getAuthParameter("password");
        //发布事件，可以监听事件进行自动注册用户
        this.publisher.publishEvent(new SmsAuthenticateBeforeEvent(integrationParams, accountName, password));
        //通过手机号码查询用户
        AppAccount sysUserAuthentication = appAccountService.applogin(accountName);
        if (sysUserAuthentication != null) {
            //发布事件，可以监听事件进行消息通知
            this.publisher.publishEvent(new SmsAuthenticateSuccessEvent(integrationParams));
        }
        return sysUserAuthentication;
    }

    @Override
    public void prepare(IntegrationParams integrationAuthentication) {

        String smsCode = integrationAuthentication.getAuthParameter("password");
        String accountName = integrationAuthentication.getAuthParameter("username");
        redisUtils.validSmsCode(accountName, smsCode);

    }

    @Override
    public boolean support(IntegrationParams integrationAuthentication) {
        return AccountTypeEnum.MOBILE.getCode().equals(integrationAuthentication.getAccountType());
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }
}
